package com.qdc.datacenters.interceptor.forest;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.qdc.datacenters.domain.QwResultVo;
import com.qdc.datacenters.enums.QwErrorCodeEnum;
import com.qdc.datacenters.exception.QwAbutmentException;
import com.qdc.datacenters.utils.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author danmo
 * @date 2024-03-01 14:36
 **/
@Slf4j
@Component
public class AgentAccessTokenInterceptor extends ForestBaseInterceptor implements Interceptor<QwResultVo> {


    /**
     * 该方法在请求发送之前被调用, 若返回false则不会继续发送请求
     */
    @Override
    public boolean beforeExecute(ForestRequest request) {

        String token = getAgentAccessToken(getCorpId(request));
        request.replaceOrAddQuery("access_token", token);
        return true;
    }


    /**
     * 请求发送失败时被调用
     *
     * @param e
     * @param forestRequest
     * @param forestResponse
     */
    @Override
    public void onError(ForestRuntimeException e, ForestRequest forestRequest, ForestResponse forestResponse) {
        log.error("onError url:{},------params:{},----------result:{}", forestRequest.getUrl(),
                JSONObject.toJSONString(forestRequest.getArguments()), forestResponse.getContent());
        if (StrUtils.isNotEmpty(forestResponse.getContent())) {
            QwAbutmentException qwAbutmentException = new QwAbutmentException(1001, forestResponse.getContent());
            throw new ForestRuntimeException(qwAbutmentException);
        } else {
            QwAbutmentException qwAbutmentException = new QwAbutmentException(-1, "网络请求超时");
            throw new ForestRuntimeException(qwAbutmentException);
        }
    }


    /**
     * 请求成功调用(微信端错误异常统一处理)
     *
     * @param resultVo
     * @param forestRequest
     * @param forestResponse
     */
    @Override
    public void onSuccess(QwResultVo resultVo, ForestRequest forestRequest, ForestResponse forestResponse) {
        QwErrorCodeEnum errorCodeEnum = QwErrorCodeEnum.parseEnum(resultVo.getErrCode());
        if (null != errorCodeEnum) {
            resultVo.setErrMsg(errorCodeEnum.getErrorMsg());
        }
        log.info("url:{},result:{}", forestRequest.getUrl(), forestResponse.getContent());
    }

    /**
     * 请求重试
     *
     * @param request  请求
     * @param response 返回值
     */
    @Override
    public void onRetry(ForestRequest request, ForestResponse response) {
        log.info("url:{}, params:{}, cause:{}, retry-num:{}", request.getUrl(), JSONObject.toJSONString(request.getArguments()), response.getContent(), request.getCurrentRetryCount());
        //当错误码符合重置token时，刷新token
        QwResultVo weResultVo = JSONObject.parseObject(response.getContent(), QwResultVo.class);
        //当错误码符合重置token时，刷新token
        if (!ObjectUtil.equal(QwErrorCodeEnum.ERROR_CODE_OWE_1.getErrorCode(), weResultVo.getErrCode())) {
            //删除缓存
            String corpId = getCorpId(request);
            removeAgentAccessToken(getCorpId(request));
            String token = getAgentAccessToken(corpId);
            request.replaceOrAddQuery("access_token", token);
        }
    }


}
